package com.mhl.campuscabinet;

import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.mhl.adapter.Comment_Adapter;
import com.mhl.client.OkHttpUtils;
import com.mhl.entity.Comment;
import com.mhl.entity.LocalData;
import com.mhl.entity.Product;
import com.mhl.entity.User;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CommentAcyivity extends Activity {

    private RecyclerView recyclerView;
    private List<Comment> clist;
    private Comment_Adapter comment_adapter;
    private Button btn_cancel;
    private LinearLayout layout;
    private EditText commentInput;
    private int itemId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        itemId = getIntent().getIntExtra("item_id",0);
        initView();
        getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);

    }

    public void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.list_comment);
        commentInput = findViewById(R.id.editcomment);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        clist = new ArrayList<>();
        //test
        //test();

        loadComment();

        comment_adapter = new Comment_Adapter(clist, this);
        recyclerView.setAdapter(comment_adapter);

        btn_cancel = (Button) this.findViewById(R.id.btn_cancel);
        layout = (LinearLayout) findViewById(R.id.pop_layout);

        //添加选择窗口范围监听可以优先获取触点，即不再执行onTouchEvent()函数，点击其他地方时执行onTouchEvent()函数销毁Activity
        layout.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "提示：点击窗口外部关闭窗口！",
                        Toast.LENGTH_SHORT).show();
            }
        });
        //添加按钮监听
        btn_cancel.setOnClickListener(new OnClickListener() {

//            if(commentInput.getText().equals("")){
//
//            }


            @Override
            public void onClick(View view) {
                //finish();
                JSONObject req = new JSONObject();

                try {

                    MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
                    req.put("user_id", User.getInstance().getUserId());
                    req.put("comment", commentInput.getText().toString());
                    req.put("merchandise_id", itemId);
                    String json = req.toString();
                    RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

                    OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp()+"comment/create", requestBody, new Callback() {
                        @Override
                        public void onFailure(@NonNull Call call, @NonNull IOException e) {
                            System.out.println(e);
                        }

                        @Override
                        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                            final String ItemsString = response.body().string();
                            String allInfo = "";
                            String beforeT = "";
                            String afterT = "";
                            try {

                                int state = 1;
                                try {
                                    JSONObject errcodeJson = new JSONObject(ItemsString);
                                    state = errcodeJson.getInt("errcode");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                Looper.prepare();
                                if (state != 0) {
                                    Toast.makeText(CommentAcyivity.this, "Can't reload ", Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(CommentAcyivity.this, "Send succeeded ", Toast.LENGTH_SHORT).show();
                                    JSONObject res = new JSONObject(ItemsString);
                                    JSONObject data = res.getJSONObject("data");

                                    Comment comment = new Comment();
                                    comment.setName(data.getString("user_name"));
                                    comment.setContent(data.getString("comment"));
                                    allInfo = data.getString("comment_time");
                                    beforeT = allInfo.substring(0,allInfo.indexOf("T"));
                                    afterT = allInfo.substring(beforeT.length()+1,beforeT.length()+6);
                                    allInfo = beforeT + "-" + afterT;
                                    comment.setTime(allInfo);
                                    clist.add(comment);
                                    CommentAcyivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
//                                        System.out.println("开始显示商品");
                                            commentInput.setText("");
                                            comment_adapter.notifyDataSetChanged();
                                        }
                                    });
                                    Looper.loop();
                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    public void test() {
        for (int i = 0; i < 10; i++) {
            Comment comment = new Comment(R.drawable.head1, "name", "time", "content");
            clist.add(comment);
        }
    }

    public void loadComment() {
        JSONObject itemJson = new JSONObject();
        clist.clear();

        try {
            MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
            itemJson.put("id", itemId);
            String json = itemJson.toString();
            RequestBody requestBody = RequestBody.Companion.create(json, mediaType);

            OkHttpUtils.sendOkHttpResponse(LocalData.getInstance().getIp()+"merchandise/get", requestBody, new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    System.out.println(e);
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String ItemsString = response.body().string();
                    String allInfo = "";
                    String beforeT = "";
                    String afterT = "";
                    try {

                        int state = 1;
                        try {
                            JSONObject errcodeJson = new JSONObject(ItemsString);
                            state = errcodeJson.getInt("errcode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Looper.prepare();
                        if (state != 0) {
                            Toast.makeText(CommentAcyivity.this, "Can't load comment page", Toast.LENGTH_SHORT).show();
                        } else {
                            JSONObject res = new JSONObject(ItemsString);
                            JSONObject data = res.getJSONObject("data");
                            JSONArray commentsArray = data.getJSONArray("comments");

                            for (int i = 0; i < commentsArray.length(); i++) {
                                JSONObject commentJson = commentsArray.getJSONObject(i);
                                Comment comment = new Comment();
                                comment.setName(commentJson.getString("name"));

                                allInfo = commentJson.getString("create_date");
                                //处理时间格式
                                beforeT = allInfo.substring(0,allInfo.indexOf("T"));
                                afterT = allInfo.substring(beforeT.length()+1,beforeT.length()+6);
                                allInfo = beforeT + "-" + afterT;

                                //temp += commentJson.getString("create_datetime").substring(11,15);
                                comment.setTime(allInfo);

                                comment.setContent(commentJson.getString("content"));

                                //comment.setUrl(commentJson.getString("url"));
                                clist.add(comment);

                            }

                            //comment_adapter.notifyDataSetChanged();
                            CommentAcyivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
//                                        System.out.println("开始显示商品");
                                    comment_adapter.notifyDataSetChanged();
                                }
                            });
                            Looper.loop();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //实现onTouchEvent触屏函数但点击屏幕时销毁本Activity
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        finish();
        return true;
    }


}

